<?php

require('../vendor/autoload.php');
//require('../vendor/php-mqtt/client/src/MqttClient.php');
use \PhpMqtt\Client\MqttClient;
use \PhpMqtt\Client\ConnectionSettings;
//use \app\admin\controller\Server;
cli_set_process_title('mqtt1');
$server   = '113.44.136.17';
$port     = 1883;
$clientId = rand(5, 15);
$username = 'test';
$password = '123456';
$clean_session = false;
$mqtt_version = MqttClient::MQTT_3_1_1;

$connectionSettings = (new ConnectionSettings)
    ->setUsername($username)
    ->setPassword($password)
    ->setKeepAliveInterval(60)
    ->setLastWillTopic('testtopic/test')
    ->setLastWillMessage('client disconnect')
    ->setLastWillQualityOfService(1);


$mqtt = new MqttClient($server, $port, $clientId, $mqtt_version);
//$mqtt = new MqttClient($server, $port, $clientId, '3.1.1');
$mqtt->connect($connectionSettings, $clean_session);
printf("client connected\n");

$mqtt->subscribe('testtopic/#', function ($topic, $message) {
    printf("Received message on topic [%s]: %s\n", $topic, $message);
    /*$model = new Server();
    $model->insert($topic,$message);*/


}, 0);

/*for ($i = 0; $i< 10; $i++) {
    $payload = array(
        'protocol' => 'tcp',
        'date' => date('Y-m-d H:i:s'),
        'url' => 'https://github.com/emqx/MQTT-Client-Examples'
    );
    $mqtt->publish(
    // topic
        'emqx/test',
        // payload
        json_encode($payload),
        // qos
        0,
        // retain
        true
    );
    printf("msg $i send\n");
    sleep(1);
}*/

$mqtt->loop(true);
